package com.cy.store.service.impl;

import com.cy.store.entity.Address;
import com.cy.store.mapper.AddressMapper;
import com.cy.store.service.IAddressService;
import com.cy.store.service.IDistrictService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 新增收货地址的实现类
 */
@Service
public class AddressServiceImpl implements IAddressService {
    @Autowired
    private AddressMapper addressMapper;

    // 在添加用户的收货地址的业务层依赖于IDistrictService的业务层接口
    @Autowired
    private IDistrictService districtService;

    @Value("${user.address.max-count}") //将定义在application的配置文件导入
    private Integer maxCount; //20


    /**
     * 添加用户的收货地址
     * @param uid
     * @param username
     * @param address
     */
    @Override
    public void addNewAddress(Integer uid , String username , Address address){
        //调用收货地址统计的方法
        Integer count = addressMapper.countByUid(uid);
        if (count>=maxCount){
            throw new AddressCountLimitException("用户收货地址超出上限");
        }

        //对address的省市区进行补齐
        String provinceName =  districtService.getNameByCode(address.getProvinceCode());
        String cityName =  districtService.getNameByCode(address.getCityCode());
        String areaName =  districtService.getNameByCode(address.getAreaCode());
        address.setProvinceName(provinceName);
        address.setCityName(cityName);
        address.setAreaName(areaName);


        //uid、isDefault
        address.setUid(uid);
        Integer isDefault = (count == 0 ? 1:0); //1 表示默认；将第一个收货地址选择为默认
        address.setIsDefault(isDefault);

        //补全4项日志
        address.setCreatedUser(username);
        address.setModifiedTime(new Date());
        address.setModifiedUser(username);
        address.setCreatedTime(new Date());

        //插入收货地址的方法
        Integer rows = addressMapper.insert(address);
        if (rows!=1){
            throw new InsertException("插入用户的收货地址时产生未知的异常");
        }
    }

    /**
     * 显示收货地址
     * @param uid
     * @return
     */
    @Override
    public List<Address> getByUid(Integer uid) {
        List<Address> list =  addressMapper.findByUid(uid);
        for (Address l : list){   //对list集合的每一个值进行操作
           //对一些不需要返回前端的数据，进行null处理
            l.setCreatedTime(null);
            l.setModifiedUser(null);
            l.setModifiedTime(null);
            l.setCreatedUser(null);
        }
        return list;
    }

    /**
     * 设置默认的收货地址
     * @param aid
     * @param uid
     * @param username
     */
    @Override
    public void setDefault(Integer aid, Integer uid, String username) {
        //判断是否存在
        Address result =  addressMapper.findByAid(aid);
        if (result ==null){
            throw new AddressNotFoundException("收货地址不存在");
        }
        //判断是否归属
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法访问");
        }
        //先将默认地址设置为0
        Integer rows =  addressMapper.updataNonDefault(uid);
        if (rows <1){
            throw new UpdateException("更新异常");
        }
        //设置默认的地址
        rows = addressMapper.updataDefaultByAid(aid,username,new Date());
        if (rows != 1){
            throw new UpdateException("更新异常");
        }
    }


    @Override
    public void delete(Integer aid, Integer uid, String username) {
        Address result = addressMapper.findByAid(aid);
        //异常判断
        if (result ==null){
            throw new AddressNotFoundException("收货地址找不到");
        }
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException("非法访问");
        }

        //执行删除+判断
        if (addressMapper.deleteByAid(aid) != 1){
            throw new DeleteException("删除数据时发生异常");
        }

        //判断是否还存在默认地址；不在则设置最新的为默认，反之不管
        if (addressMapper.getIsDefaultAddress(uid) == null){
            if (addressMapper.countByUid(uid) == 0){
                return;
            }else {
                Address address1 = addressMapper.findLastModified(uid);
                addressMapper.updataDefaultByAid(address1.getAid(),username,new Date());
            }
        }
    }

    @Override
    public Address getByAid(Integer aid, Integer uid) {
// 根据收货地址数据id，查询收货地址详情
        Address address = addressMapper.findByAid(aid);
        if (address == null) {
            throw new AddressNotFoundException("尝试访问的收货地址数据不存在");
        }
        if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException("非法访问");
        }
        address.setProvinceCode(null);
        address.setCityCode(null);
        address.setAreaCode(null);
        address.setCreatedUser(null);
        address.setCreatedTime(null);
        address.setModifiedUser(null);
        address.setModifiedTime(null);
        return address;
    }



    }
